//
//  POObjectExtensions.m
//  POBase
//
//  Created by Pieter Omvlee on 6/4/08.
//  Copyright 2008 Bohemian Coding. All rights reserved.
//

#import "CHObjectExtensions.h"


@implementation NSObject (CHObjectPerform)

- (id)performSelector:(SEL)sel withObjects:(NSArray *)args
{
  switch([args count]) {
    case 0: return [self performSelector:sel];
    case 1: return [self performSelector:sel withObject: [args objectAtIndex:0]];
    case 2: return [self performSelector:sel withObject: [args objectAtIndex:0] withObject:[args objectAtIndex:1]];
    case 3: return objc_msgSend(self, sel, [args objectAtIndex:0], [args objectAtIndex:1], [args objectAtIndex:2]);
    case 4: return objc_msgSend(self, sel, [args objectAtIndex:0], [args objectAtIndex:1], [args objectAtIndex: 2], [args objectAtIndex:3]);
    case 5: return objc_msgSend(self, sel, [args objectAtIndex:0], [args objectAtIndex:1], [args objectAtIndex: 2], [args objectAtIndex:3], [args objectAtIndex:4]);
    case 6: return objc_msgSend(self, sel, [args objectAtIndex:0], [args objectAtIndex:1], [args objectAtIndex: 2], [args objectAtIndex:3], [args objectAtIndex:4], [args objectAtIndex:5]);
    default: [NSException raise:@"ToManyArgumentsException" format:@"performSelector:withObjects: called with too many arguments. Add more case statements."]; break;
  }
  return nil;
}

- (id)performSelector:(SEL)sel withObjects:(NSArray *)args iterateOverIndex:(int)index
{
  NSArray *iterator       = [args objectAtIndex:index];
  NSMutableArray *result  = [NSMutableArray array];
  NSMutableArray *newArgs = [[args mutableCopy] autorelease];
  
  NSUInteger i, count = [iterator count];
  for (i = 0; i < count; i++) {
    [newArgs replaceObjectAtIndex:index withObject:[iterator objectAtIndex:i]];
    [result addObject:[self performSelector:sel withObjects:newArgs]];
  }
  return result;
}

@end
